package com.huifaapp.mall.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.JSConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.base.activity.BaseActivity;
import com.huifaapp.mall.base.basemvp.IPresenter;
import com.huifaapp.mall.bean.MessageEvent;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.js.AndroidInterface;
import com.huifaapp.mall.uitils.AppManager;
import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

public class WebActivity extends BaseActivity {

    public static final String KEY_URL = "KEY_URL";
    public static final String KEY_TOKEN = "TOKEN";
    private String mUrl;
    private String mToken;
    private LinearLayout ll_web_container;
    protected AgentWeb mAgentWeb;
    LoadingDialog loadingDialog;
    private boolean isExit = false;
    WebView mWebView;

    @Override
    public void onStart() {
        super.onStart();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event != null && !TextUtils.isEmpty(event.getMesg())) {
//            mWebView.clearHistory();
            //跳转支付成功的页面
            mWebView.goBack();   //后退
            mAgentWeb.getLoader().loadUrl(event.getMesg());

        }

        /* Do something */
    }

    ;

    @Override
    public void onStop() {
        super.onStop();

    }

    protected String getUrl() {
//        mUrl= getIntent().getExtras().getString(KEY_URL);

//        return "http://192.168.199.200:3000/eastsRetreat/html/setup.html";

        return ApiManager.BASE_HTML_URL + JSConstants.HTML_HOME;
//        return "file:///android_asset/js_interaction/hello.html";
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        super.initViews(savedInstanceState);

        Log.v("shiran","APP.isDebug======"+ APP.isDebug);


        ll_web_container = (LinearLayout) findViewById(R.id.ll_web_container);



        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(ll_web_container, new LinearLayout.LayoutParams(-1, -1))//
//                .setCustomIndicator(dialog)//自定义进度条
                .useDefaultIndicator()// 使用默认进度条
                .setIndicatorColor(R.color.color_common_base)//进度条颜色
//                .defaultProgressBarColor()//使用默认进度条颜色
                .setReceivedTitleCallback(mCallback)//设置 Web 页面的 title 回调
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setSecutityType(AgentWeb.SecurityType.strict)
//                .setWebLayout(new WebLayout(this))

                .createAgentWeb()//.ready();
                .go(getUrl());
        mWebView = mAgentWeb.getWebCreator().get();
        mWebView.getSettings().setJavaScriptEnabled(true);
        addJsHolder();

//        if (mAgentWeb != null) {
////            mAgentWeb.getJsInterfaceHolder().addJavaObjects(,)
//            mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, this));
////            mAgentWeb.getJsInterfaceHolder().addJavaObject("android ",new AndroidInterface(mAgentWeb,getApplicationContext()));
//
//        }
//        Handler handler = new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
////                if (mAgentWeb != null) {
////                    mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, getApplicationContext()));
//////                    mAgentWeb.getJsInterfaceHolder().addJavaObject("android ",new AndroidInterface(mAgentWeb,getApplicationContext()));
////
////                }
////                mAgentWeb.getJsEntraceAccess().quickCallJs("getToken",mToken);
//                mAgentWeb.getJsEntraceAccess().quickCallJs("callByAndroidInteraction", "你好Js");
//
//                mAgentWeb.getJsEntraceAccess().quickCallJs("sum", new ValueCallback<String>() {
//                    @Override
//                    public void onReceiveValue(String value) {
//                        ToastUtils.showShortSafe("返回值是>>" + value);
//                    }
//                }, "2", "3");
//            }
//        }, 2000);
//        mAgentWeb.getJsEntraceAccess().quickCallJs("getToken","Hello ! Agentweb");


    }

    /**
     * 调用JS 方法
     *
     * @param url
     */
    private void getJsEntraceAccess(String url) {


        if ((ApiManager.BASE_HTML_URL + JSConstants.HTML_HOME).equals(url)) {//首页
            mAgentWeb.getJsEntraceAccess().quickCallJs(JSConstants.GET_TOKEN, mToken);
//            mAgentWeb.getJsEntraceAccess().quickCallJs(JSConstants.GET_TOKEN, "2017111721244178436fe4a7361491478c98b503e88f696b15");
        }

//            switch (url) {
//                case (ApiManager.BASE_HTML_URL+ JSConstants.HTML_HOME): //首页
//                    mAgentWeb.getJsEntraceAccess().quickCallJs(JSConstants.GET_TOKEN,mToken);
//                    break;
//                default:
//
//                    break;
//            }

    }

    /**
     * 添加Js需要调用的方法
     */
    private void addJsHolder() {
        if (mAgentWeb != null) {
            //注入JS需要调用的代码
            mAgentWeb.getJsInterfaceHolder().addJavaObject(JSConstants.JS_ALIAS, new AndroidInterface(mAgentWeb, this));
        }
    }

    @Override
    protected IPresenter onLoadPresenter() {
        return null;
    }

    @Override
    protected void initData(Bundle bundle) {
        EventBus.getDefault().register(this);
        if (bundle!=null) {
            mToken = (String) bundle.get(KEY_TOKEN);
        }
    }


    private ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
//            LogUtils.e(TAG,"title>>"+title);
        }
    };
    /**
     * Webview自己处理超链接(Webview的监听器非常多，封装一个特殊的监听类来处理)
     */
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return super.shouldInterceptRequest(view, request);
        }

        /**
         * 当打开超链接的时候，回调的方法
         * WebView：自己本身webView
         * url：即将打开的url
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
        /*    //自己处理新的url
            webView.loadUrl(url);
            //true就是自己处理
            return true;*/
            if ((ApiManager.BASE_HTML_URL + JSConstants.HTML_SET).equals(url)) {
                //设置页面跳转自己的页面
                //true就是自己处理
//                gotoActivity(InputInviteCodeActivity.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(WebActivity.this, SettingActivity.class);
                        startActivity(intent);
                    }
                });

                return true;
            } else {

                return super.shouldOverrideUrlLoading(view, url);
            }
        }
        //重写页面打开和结束的监听。打开时弹出菊花

        /**
         * 界面打开的回调 可以加载菊花
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            //显示对话框
            LogUtils.e("Info", "BaseWebActivity onPageStarted");
            if (null != loadingDialog && !loadingDialog.isShowing()) {
                loadingDialog.show();
            }
        }

        /**
         * 重写页面打开和结束的监听。打开时弹出菊花，关闭时隐藏菊花
         * 界面打开完毕的回调
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            if (null != loadingDialog && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
            getJsEntraceAccess(url);
            //
        }

        /**
         * 网页加载失败的时候处理
         * @param view
         * @param request
         * @param error
         */
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }


    };

    /**
     * 设置进度条
     * WebChromeClient与webViewClient的区别
     * webViewClient处理偏界面的操作：打开新界面，界面打开，界面打开结束
     * WebChromeClient处理偏js的操作
     * <p>
     * 重绘alert、confirm和prompt的弹出效果之后，在对话框结束之后一定要调用result.confirm()或者result.cancel()两个方法中的一个
     */


    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        /**
         * 进度改变的回调
         * WebView：就是本身
         * newProgress：即将要显示的进度
         */
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
            LogUtils.e("Info", "progress:" + newProgress);
        }
/**
 * 重写alert、confirm和prompt的弹出效果，并把用户操作的结果回调给JS
 */
        /**
         * Webview加载html中有alert()执行的时候，会回调这个方法
         * url:当前Webview显示的url
         * message：alert的参数值
         * JsResult：java将结果回传到js中
         */
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {


            //返回true  代表自己处理
            return super.onJsAlert(view, url, message, result);
        }

        /**
         * Webview加载html中有confirm执行的时候，会回调这个方法
         * url:当前Webview显示的url
         * message：alert的参数值
         * JsResult：java将结果回传到js中
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            //返回true  代表自己处理
            return super.onJsConfirm(view, url, message, result);
        }

        /**
         * Webview加载html中有prompt()执行的时候，会回调这个方法
         * url:当前Webview显示的url
         * message：alert的参数值
         *defaultValue就是prompt的第二个参数值，输入框的默认值
         * JsPromptResult：java将结果重新回传到js中
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            //返回true  代表自己处理
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                ToastUtils.showShortSafe("再按一次退出应用");
                isExit = true;
            } else {
                AppManager.getAppManager().AppExit(getApplicationContext(), false);
            }

            Observable.
                    timer(2, TimeUnit.SECONDS)
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            isExit = false;
                        }
                    });


            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        LogUtils.e("Info", "result:" + requestCode + " result:" + resultCode);
        mAgentWeb.uploadFileResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_base_web;
    }


}
